package com.hhit.bigscreenbackmanage.service.impl.tgygl;

import com.alibaba.fastjson.JSONObject;
import com.hhit.bigscreenbackmanage.dao.tgygl.TgyglFileMapper;
import com.hhit.bigscreenbackmanage.entity.tgygl.TgyglFileEntity;
import com.hhit.bigscreenbackmanage.service.tgygl.TgyglService;
import com.hhit.bigscreenbackmanage.util.PageUtil;
import org.seimicrawler.xpath.JXNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class TgyglServiceImpl implements TgyglService, ApplicationListener<WebServerInitializedEvent> {

    private Logger log = LoggerFactory.getLogger(TgyglServiceImpl.class);

    @Autowired
    private TgyglFileMapper tgyglFileMapper;


    private int serverPort;

    @Override
    public Map<String, Object> uploadFile(MultipartFile[] file) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        MultipartFile file1 = file[0];
        //判断文件是否为空
        if (file1.isEmpty()) {
            resultMap.put("flag", false);
            return resultMap;
        }

        //创建输入输出流
        InputStream inputStream = null;
        OutputStream outputStream = null;

        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        try {
            //指定上传的位置为 d:/upload/
            String path = "src/main/resources/static/upload/tgygl/";
            //获取文件的输入流
            inputStream = file1.getInputStream();
            //获取上传时的文件名
            String fileName = file1.getOriginalFilename();
            //注意是路径+文件名
            File targetFile = new File(path + fileName);
            //如果之前的 String path = "d:/upload/" 没有在最后加 / ，那就要在 path 后面 + "/"

            //判断文件父目录是否存在
            if (!targetFile.getParentFile().exists()) {
                //不存在就创建一个
                targetFile.getParentFile().mkdir();
            }
            //获取文件的输出流
            outputStream = new FileOutputStream(targetFile);
            //最后使用资源访问器FileCopyUtils的copy方法拷贝文件
            FileCopyUtils.copy(inputStream, outputStream);

            resultMap.put("flag", true);
            resultMap.put("fileName", file1.getOriginalFilename());
            resultMap.put("fileUri", "http://" + address.getHostAddress() + ":" + this.serverPort + "/static/upload/tgygl/" + file1.getOriginalFilename());

        } catch (Exception e) {
            resultMap.put("flag", false);
            log.error(e.getMessage());
        } finally {
            //无论成功与否，都有关闭输入输出流
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultMap;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }

    @Override
    public Map<String, Object> insertFile(TgyglFileEntity entity) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            int scount = tgyglFileMapper.insertFile(entity);
            resultMap.put("flag", true);
            resultMap.put("id", entity.getId());
        } catch (Exception e) {
            resultMap.put("flag", false);
            log.error(e.getMessage());
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> queryAllByLimit(JSONObject jsonObject) {

        Map<String, Object> map = new HashMap<>();
        //先查询总条数
        //获取查询条件
        PageUtil page = new PageUtil();
        int count = tgyglFileMapper.queryAllCount(jsonObject);
        // 每页数
        page.pageCount = Integer.parseInt(jsonObject.get("pageSize").toString());
        //参数1：总行数，参数2：当前页
        page.init(count, Integer.parseInt(jsonObject.get("pageNo").toString()));
        jsonObject.put("rowNum", page.getRowNum());
        jsonObject.put("pageCount", page.getPageCount());
        List<TgyglFileEntity> tgyglFileEntities = tgyglFileMapper.queryAll(jsonObject);
        map.put("page", page);
        map.put("list", tgyglFileEntities);
        return map;
    }


    @Override
    public int deleteByPrimaryKey(Integer id) {
        return tgyglFileMapper.deleteByPrimaryKey(id);
    }

    @Override
    public TgyglFileEntity initTitles(List<JXNode> jxNode) {
        TgyglFileEntity bean = new TgyglFileEntity();
        System.out.println(bean);

        //信息标题拆分
        AtomicInteger gcjzIndex = new AtomicInteger();
        AtomicInteger glgzIndex = new AtomicInteger();
        AtomicInteger gzdpIndex = new AtomicInteger();
        AtomicInteger zdgzIndex = new AtomicInteger();

        //附件表格标题拆分
        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOnePointOneIndex = new AtomicInteger(); //附件1.1
//        AtomicInteger fjOnePointTwoIndex = new AtomicInteger(); //附件1.2
//        AtomicInteger fjOnePointThreeIndex = new AtomicInteger(); //附件1.3
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
//        AtomicInteger fjOneIndex = new AtomicInteger(); //附件1
        AtomicInteger fjIndex = new AtomicInteger(); //附件


        List<String> fjTitles = new ArrayList<String>();


        jxNode.forEach(item->{
            if (item.toString().indexOf("月份工程进展")!=-1) { //
                gcjzIndex.set(jxNode.indexOf(item));
                bean.setGcjzTitle(item.toString());
            }
            if (item.toString().indexOf("月份管理工作")!=-1) { //
                glgzIndex.set(jxNode.indexOf(item));
                bean.setGlgzTitle(item.toString());
            }
            if (item.toString().indexOf("月份工作点评")!=-1) { //
                gzdpIndex.set(jxNode.indexOf(item));
                bean.setGzdpTitle(item.toString());
            }
            if (item.toString().indexOf("月份重点工作")!=-1) { //
                zdgzIndex.set(jxNode.indexOf(item));
                bean.setZdgzTitle(item.toString());
            }
            if (item.toString().indexOf("附件")!=-1) {
                fjTitles.add(item.toString());
            }
        });
        String sp = fjTitles.toString().substring(1, fjTitles.toString().length()-1);
        bean.setFjTableTitles(sp);
        return bean;
    }

    @Override
    public TgyglFileEntity selectByPrimaryKey(Integer id) {
        TgyglFileEntity entity = tgyglFileMapper.selectByPrimaryKey(id);
        return entity;
    }
}
